﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading;

namespace ExtendedEditor.Threading
{
	public class BackgroundThread: DependencyObject, IDisposable
	{
		#region Constructors properties

		public BackgroundThread()
		{
			thread = new Thread(BackgroundThreadProc);
			commandEvent = new AutoResetEvent(false);
			queue = new Queue<BTCommandRequest>();

			thread.Start();
		}

		#endregion

		#region Second thread comands

		protected void EnqueueCommand(BTCommandRequest command)
		{
			lock (queue) queue.Enqueue(command);
			commandEvent.Set();
		}

		private BTCommandRequest DequeueCommand()
		{
			BTCommandRequest result = null;
			lock (queue) result = queue.Dequeue();
			return result;
		}

		protected void Response(BTCommandResponse command)
		{
			this.Dispatcher.Invoke(
				new BTCommandResponseDelegate(OnBTCommandResponse), 
				command);
		}

		private void ShutDown()
		{
			lock (queue) queue.Clear();
			EnqueueCommand(new BTExitCommand());
		}

		private

		#endregion

		#region Background thread procedure

		void BackgroundThreadProc()
		{
			while (true)
			{
				commandEvent.WaitOne();
				BTCommandRequest command = DequeueCommand();
				if (command is BTExitCommand) break;
				OnBTCommandRequest(command);
			}
		}

		protected virtual void OnBTCommandRequest(BTCommandRequest command)
		{ 
			//Dispatcher.Invoke(
		}

		protected virtual void OnBTCommandResponse(BTCommandResponse command)
		{
			//Dispatcher.Invoke(
		}
		#endregion
		
		#region IDisposable Members

		public void Dispose()
		{
			if (thread.IsAlive) ShutDown();
		}

		#endregion

		private Queue<BTCommandRequest> queue;
		private AutoResetEvent commandEvent;
		private Thread thread;
	}
}
